package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author mwj
 * @date 2021/11/24
 * @TIME:11:26
 */

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @PostMapping
    public R add(@RequestBody Category category){
        //正常先查 判断 再增  但因为做了全局异常处理
        categoryService.save(category);
        return R.success("新增分类成功");

    }

    @GetMapping("/page")
    public R findByPage(Integer page, Integer pageSize){

        IPage<Category> ipage=new Page<>(page,pageSize);
        LambdaQueryWrapper<Category> wrapper=new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Category::getSort);
        IPage<Category> page1 = categoryService.page(ipage, wrapper);
        return R.success(page1);
    }


    @DeleteMapping
    public R deleteById(Long id){

        //categoryService.removeById(id);

        categoryService.delete(id);


        return R.success("删除成功");
    }
    @PutMapping
    public R update(@RequestBody Category category){
        categoryService.updateById(category);

        return R.success("修改成功");
    }


    @GetMapping("/list")
    public R list(Integer type){
        //1.根据分类的类型查询所有的分类数据

        LambdaQueryWrapper<Category> wrapper=new LambdaQueryWrapper<>();
        if(type!=null){
            wrapper.eq(Category::getType,type);
        }
        List<Category> list = categoryService.list(wrapper);


        return R.success(list);
    }
}

